/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.cloudfarming.sensor.util.filesystemmonintor;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import nl.cloudfarming.sensor.ReceiverAlreadyRegisteredException;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


import nl.cloudfarming.sensor.Receiver;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

public final class FileSystemMonitor {

    private Timer timer;
    private List<Receiver> receivers;
    private volatile static FileSystemMonitor instance;
    private List<DirProperties> propertyList;
    private static Log log = LogFactory.getLog(FileSystemMonitor.class);

    public static FileSystemMonitor getInstance() {
        // needed because once there is singleton available no need to acquire
        // monitor again & again as it is costly
        synchronized (FileSystemMonitor.class) {
            // this is needed if two threads are waiting at the monitor at the
            // time when singleton was getting instantiated
            if (instance == null) {
                instance = new FileSystemMonitor();
            }
        }
        return instance;
    }

    private FileSystemMonitor() {
        receivers = new ArrayList();
        propertyList = new ArrayList();

    }

    public void adDirProperty(String directory, long pollingRate, long pollingDelay) throws RegisterDirectoryException{
        File file = new File(directory);
        if (file.exists()) {
            propertyList.add(new DirProperties(file, pollingRate, pollingDelay));
        } else if(file.mkdir()){
            propertyList.add(new DirProperties(file, pollingRate, pollingDelay));
        } else {
            log.error("Unable to read specified directory " + directory);
            throw new RegisterDirectoryException("Unable to read specified directory " + directory);
        }
    }

    public void removeDirProperty(String directory, long pollingRate, long pollingDelay) throws RemoveDirPropertyException{
        Iterator <DirProperties> d = propertyList.iterator();
        while(d.hasNext()){
            DirProperties dirProps = d.next();
            if(dirProps.getDirectory().getPath().equals(directory) && dirProps.getPollingRate() == pollingRate && dirProps.getPollingDelay() == pollingDelay){
                d.remove();
                return;
            }
        }
        log.error("Unable to remove directory properties.");
        throw new RemoveDirPropertyException("Unable to remove directory properties.");
    }

    public List<Receiver> getReceivers(){
        return receivers;
    }

    public void registerReceivers(Receiver receiver) throws ReceiverAlreadyRegisteredException{
        for (Receiver r : receivers) {
            if (r == receiver) {
                log.error("Receiver already registered");
                throw new ReceiverAlreadyRegisteredException("Receiver already registered");
            }
        }
        receivers.add(receiver);
    }

    public void removeReceiver(Receiver receiver) {
        receivers.remove(receiver);
    }

    public void start() {
        timer = new Timer(false);
        for (DirProperties dirProps : propertyList) {
            timer.schedule(new FileMonitorNotifier(dirProps.getDirectory()), dirProps.getPollingRate(), dirProps.getPollingDelay());
        }
    }

    public void stop() {
        timer.cancel();
    }

    private class FileMonitorNotifier extends TimerTask {

        private File directory;
        private long lastModified;

        public FileMonitorNotifier(File directory) {
            this.directory = directory;
            lastModified = directory.lastModified();
        }

        private boolean isChanged() {
            return lastModified != directory.lastModified() ? true : false;
        }

        @Override
        public void run() {
            if (isChanged()) {
                for (Receiver r : receivers) {
                    for(File file : directory.listFiles()){
                        try {
                            r.receive(file);
                        } catch (NoSuchAlgorithmException ex) {
                            log.error("Cryptographic algorithm not availible.",ex);
                        } catch (IOException ex) {
                            log.error("Ioexception occured",ex);
                        }
                    }                 
                }
                lastModified = directory.lastModified();
            }
        }
    }
}
